<template>
    <div class="role-container">
        <div class="search-box">
            <div class="left">
                <span>{{ t('page.user.userName') }}</span>
                <el-input class="input" v-model="roleParams.filter" :placeholder="t('page.user.placeholder')" clearable />
            </div>
            <div class="right">
                <el-button @click="resetClick">{{  t('page.user.reset') }}</el-button>
                <el-button type="primary" @click="roleParams.pageIndex = 1; getAllRoles();">{{ t('page.user.search') }}</el-button>
            </div>
        </div>
        <div class="table-content">
            <div class="table-title">
                <el-button class="mr" type="primary" :icon="Plus"  @click="editType='add';editObject=null; dialogVisible=true">{{ t('page.user.create') }}</el-button>
                <TableSetting @change="colunmChange" :handleColumnData="handleTableData"/>
            </div>
            <div class="table-box" ref="tableBox">
                <el-table border :max-height="tableHeight" :data="roles" style="width: 100%">
                    <el-table-column fixed="left" v-if="handleTableData.showSelection" type="selection" width="55" />
                    <el-table-column fixed="left" v-if="handleTableData.showIndex" type="index" width="50" />
                    <el-table-column :fixed="val.fixed ? val.fixedDir : false" :label="t(`page.role.${val.name}`)" v-for="(val,index) in filterList" :key="index">
                        <template #default="scope">
                            <el-tag v-if="val.name === 'isDefault'" class="ml-2" :type="scope.row.isDefault ?  'success' : 'danger'">是</el-tag>
                            <template v-else>
                                {{ scope.row[val.name] }}
                            </template>
                        </template>
                    </el-table-column>
                    <el-table-column :label="t('page.role.action')">
                        <template #default="scope">
                            <el-button size="small"
                                       @click="roleId = scope.row.id;drawerVisible=true;"
                            >{{  t('page.role.permission') }}</el-button
                            >
                            <el-button size="small"
                                       @click="handleEditClcik(scope.$index, scope.row)"
                            >{{  t('page.role.edit') }}</el-button
                            >
                            <el-button
                                size="small"
                                type="danger"
                                @click="handleDelete(scope.$index, scope.row)"
                            >{{  t('page.role.delete') }}</el-button
                            >
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <div class="pagination-box">
                <el-pagination
                    v-model:current-page="roleParams.pageIndex"
                    v-model:page-size="roleParams.pageSize"
                    :page-sizes="[10, 20, 30, 40]"
                    :small="true"
                    :background="false"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="totalCount"
                    @size-change="getAllRoles"
                    @current-change="getAllRoles"
                />
            </div>
        </div>

        <RoleDialog @hanldeRequest="getAllRoles" :type="editType" :editObject="editObject" v-model:dialogVisible="dialogVisible"/>
        <RoleMenuDialog :routeDatas="routeDatas" :roleId="roleId" v-model:dialogVisible="dialogMenuVisible"/>
        <AuthDrawer :roleId="roleId" :routeDatas="routeDatas" v-model:drawerVisible="drawerVisible"/>
    </div>
</template>

<script setup>
import RoleDialog from "./components/RoleDialog.vue"
import RoleMenuDialog from "./components/RoleMenuDialog.vue"
import AuthDrawer from "./components/AuthDrawer.vue"
import {Plus} from '@element-plus/icons-vue';

import { ElMessage, ElMessageBox } from 'element-plus'

import { reactive, ref, watch,onUnmounted,onMounted,computed } from 'vue'
import {rolesAll,rolesDelete,rolesPage} from "@/api/roles"
import {menuHook} from "@/hooks/menu"
import { useI18n } from '@/hooks/usel18n';
import TableSetting from '@/components/TableSetting/index.vue'

defineOptions({
  name: "Role",
});
const { t } = useI18n();
const drawerVisible = ref(false);
const dialogVisible = ref(false);
const dialogMenuVisible = ref(false);
const editType = ref('add');
const editObject = ref(null);
const roleId = ref('');
const roles = ref([]);
const tableHeight = ref(100)
const tableBox = ref();
function handleAdd() {
  editType.value = 'add';
  editObject.value = null;
  dialogVisible.value = true;
}

const roleParams = ref({
  filter:'',
  pageIndex:1,
  pageSize:10
})
const totalCount = ref(0)

const handleTableData = ref({
  showIndex:true,
  showSelection:false,
  list:[
    {
      name:'name',
      show:true,
      fixed:false,
      fixedDir:'',
      title:'page.role.name'
    },
    {
      name:'isDefault',
      show:true,
      fixed:false,
      fixedDir:'',
      title:'page.role.isDefault'
    }
  ]
})

const filterList = computed(() => {
  const arr = []
  let sortIndex = -100;
  handleTableData.value.list.forEach((element,index) => {
    if(element.show) {
      if(element.fixed) {
        if(element.fixedDir === 'left') {
          element.sortIndex = sortIndex + index;
        }else if(element.fixedDir === 'right') {
          element.sortIndex = index - sortIndex;
        }
      }else{
        element.sortIndex = index
      }
      arr.push(element)
    }
  });
  return arr.sort((item1,item2) => {
    return item1.sortIndex - item2.sortIndex
  });
})

function colunmChange(v) {
  handleTableData.value = v;
}

function resetClick() {
  roleParams.value = {
    filter:'',
    pageIndex:1,
    pageSize:10
  }
  getAllRoles();
}


async function getAllRoles() {
  const res = await rolesPage(roleParams.value);
  roles.value = res.items;
  totalCount.value = res?.totalCount ?? 0;
}
getAllRoles();

const {routeDatas} = menuHook();

function handleMenuClick(index,row) {
  dialogMenuVisible.value = true;
  roleId.value = row.id;

}

function handleEditClcik(index,row) {
  editObject.value = row;
  editType.value = 'edit';
  dialogVisible.value = true;
}

function handleDelete(index,row) {

  ElMessageBox.confirm(
    '是否删除?',
    'Warning',
    {
      confirmButtonText: 'OK',
      cancelButtonText: 'Cancel',
      type: 'warning',
    }
  )
    .then(async () => {
      await rolesDelete({id:row.id})
      ElMessage({
        type: 'success',
        message: 'Delete completed',
      })
      getAllRoles();
    })


}

function resetHeight() {
  tableHeight.value = tableBox.value.offsetHeight;
}

onMounted(() => {
  tableHeight.value = tableBox.value.offsetHeight;
  window.addEventListener("resize", resetHeight);
})

onUnmounted(() => {
  window.removeEventListener("resize", resetHeight);
})


</script>

<style lang="scss" scoped>
.role-container {
  padding: 16px;
  height: 100%;
  box-sizing: border-box;
  >.search-box {
    background-color: #fff;
    height: 40px;
    box-sizing: content-box;
    padding: 12px 10px 6px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    >.left {
      display: inline-flex;
      align-items: center;
      >span {
        flex-shrink: 0;
        margin-right: 10px;
      }
      >.input {
        width: 250px;
      }

    }
    >.right {
      display: inline-flex;
      align-items: center;
    }
  }

  >.table-content {
    box-sizing: border-box;
    margin-top: 16px;
    background-color: #fff;
    padding: 6px;
    border-radius: 2px;
    height: calc(100% - 74px);
    >.table-title {
      height: 32px;
      padding-bottom: 8px;
      box-sizing: content-box;
      display: flex;
      align-items: center;
      justify-content: flex-end;
      .mr {
        margin-right: 10px;
      }
    }
    >.table-box {
      height: calc(100% - 74px);
      >.table {
       // max-height:100%;
       // height: 100%;
      }
    }
    >.pagination-box {
      margin-top: 10px;
      display: flex;
      justify-content: center;
    }
  }

}


</style>